unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    Image1: TImage;
    Button1: TButton;
    Timer1: TTimer;
    ScrollBar1: TScrollBar;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure ScrollBar1Change(Sender: TObject);
  private
    { Private declarations }
  public
    procedure Draw;
  end;
const
xo = 40;
yo = 20;
h = 5;
w = 10;
var
  Form1: TForm1;
  a : array of integer;
  n : integer;
  step, step2 : integer;
  flag : boolean;
implementation

{$R *.dfm}

procedure TForm1.Draw;
var i : integer;
begin
  for i:=0 to n-1 do
  begin
    if (i = step2) or (i = step2+1) then
    begin
      Form1.Image1.Canvas.Brush.Color := clRed;
    end;
    if (i > n-1-step) or (step=n-2) or ((step2+1=n-1-step)and(flag=false)) then
    begin
      Form1.Image1.Canvas.Brush.Color := clBlue;
    end;
    Form1.Image1.Canvas.Rectangle(xo+w*i, yo, xo+w*(i+1), yo+h*a[i]);
    Form1.Image1.Canvas.Brush.Color := clWhite;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var i : integer;
begin
  randomize;
  n := 40;
  setlength(a, n);
  for i:=0 to n-1 do
    a[i] := random(50);
  step := 0;
  step2 := 0;
  flag := false;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  TForm1.Create(Form1);
  Timer1.Enabled := True;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var k : integer;
begin
  if a[step2] > a[step2+1] then
  begin
    k := a[step2];
    a[step2] := a[step2+1];
    a[step2+1] := k;
    flag := true;
  end;
  Image1.Canvas.Rectangle(Image1.ClientRect);
  Draw;
  step2 := step2+1;
  if step2 = n-1-step then
  begin
    step2 := 0;
    step := step+1;
    if flag = false then
      Timer1.Enabled := False;
  end;
  if step = n-1 then
    Timer1.Enabled := False;
end;

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  Timer1.Interval := ScrollBar1.Position*10;
end;

end.
